import { createUniFetch } from "uni-app-fetch";
import useUserStore from "@/pinia/modules/userStore";

/*tabBar页面的路径*/
const tabBarPagePaths = [
  "pages/task/index",
  "pages/message/index",
  "pages/my/index",
];

/*调用createUniFetch()函数创建一个uniFetch*/
const uniFetch = createUniFetch({
  /* loading状态 */
  loading: {
    title: "加载中···",
  },
  /* 请求基础地址 */
  baseURL: "https://slwl-api.itheima.net",
  /*配置请求拦截器以及响应拦截器*/
  intercept: {
    /* 请求拦截器 */
    request(options) {
      const userStore = useUserStore();
      const defaultHeader = {
        Authorization: userStore.token,
      };
      options.header = Object.assign({}, defaultHeader, options.header);
      return options;
    },
    /* 响应拦截器 */
    response({ data, statusCode }) {
      if (statusCode === 401) {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const routerType = tabBarPagePaths.includes(currentPage.route) ? "switchTab" : "redirectTo";
        uni.redirectTo({ url: `/pages/login/index?return_url=/${currentPage.route}&routerType=${routerType}` });
      } else if (data.code !== 200) {
        return Promise.reject(new Error(data.msg));
      } else {
        return data;
      }
    },
  },
});

/* 模块导出 */
export default uniFetch;
